﻿using System;
using System.Data.SqlClient;
using System.Linq;
using DHYHN.ASPNET.HoiNghi.DAL;

namespace DHYHN.ASPNET.HoiNghi.BIZ
{
    public class InformationHelper:DbHelper
    {
        public Information GetInformation(int id,string lang)
         {
             try
             {

                 return _dataContext.GetTable<Information>().Where(a => a.Id == id && a.Lang==lang).SingleOrDefault();
             }
             catch (Exception exception)
             {
                 
                 throw new Exception(exception.Message,exception);
             }
         }

        public void SaveInformation(Information info)
        {
            try
            {
                var temp = _dataContext.GetTable<Information>().Where(a => a.Id == info.Id && a.Lang==info.Lang).SingleOrDefault();

                temp.Title=info.Title;
                temp.Body = info.Body;
                _dataContext.SubmitChanges();

            }
            catch (Exception exception)
            {

                throw new Exception(exception.Message, exception);
            }
        }

        public void DeleteInformation(Information info)
        {
            try
            {
                var lang = new string[] {"en","fn","vn"};
                foreach (string s in lang)
                {
                    var temp = _dataContext.GetTable<Information>().Where(a => a.Id == info.Id && a.Lang == s).SingleOrDefault();
                    if (temp != null) _dataContext.GetTable<Information>().DeleteOnSubmit(temp);
                }

                _dataContext.SubmitChanges();
            }
            catch (Exception exception)
            {
                throw new Exception(exception.Message, exception);
            }
        }

        public void CreateInformation(Information infoEn,Information infoFn, Information infoVn)
        {
            try
            {
                var temp = _dataContext.GetTable<Information>().OrderByDescending(a => a.Id).Take(1).Single();
                infoEn.Id = temp.Id + 1;
                infoFn.Id = temp.Id + 1;
                infoVn.Id = temp.Id + 1;
                _dataContext.GetTable<Information>().InsertOnSubmit(infoEn);
                _dataContext.GetTable<Information>().InsertOnSubmit(infoFn);
                _dataContext.GetTable<Information>().InsertOnSubmit(infoVn);
                _dataContext.SubmitChanges();
            }
            catch (Exception exception)
            {
                throw new Exception(exception.Message,exception);
            }
        }
    }
}